package com.atguigu.crowd.mvc.config;/*
 *ClassNmae:CrowdExceptionResolver
 *Package:com.atguigu.crowd.mvc.config
 *Description:
 *@Date:2020/6/15 19:47
 *@Author:1519524541@qq.com
 */

import com.atguigu.crowd.util.CrowdConstant;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import com.google.gson.Gson;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@ControllerAdvice表示当前类是一个基于注解的异常处理器类
@ControllerAdvice
public class CrowdExceptionResolver {
    @ExceptionHandler(value = ArithmeticException.class)
    public ModelAndView resolveMathException(HttpServletResponse response,HttpServletRequest request,
                                             NullPointerException exception) throws IOException {
        String viewName = "system-error";
        return commonResolve(viewName,exception,response,request);
    }
    @ExceptionHandler(value = NullPointerException.class)
    public ModelAndView resolveNullPointerException(HttpServletResponse response,HttpServletRequest request,
                                                    NullPointerException exception) throws IOException {
        String viewName = "system-error";
        return commonResolve(viewName,exception,response,request);
    }







    private ModelAndView commonResolve(String viewName,Exception exception,HttpServletResponse response,
                                       HttpServletRequest request) throws IOException {
        boolean judgeResult = CrowdUtil.judgeRequestType(request);
        if(judgeResult){
            ResultEntity<Object> resultEntity = ResultEntity.failed(exception.getMessage());
            Gson gson = new Gson();
            String json = gson.toJson(resultEntity);
            response.getWriter().write(json);
            return null;
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject(CrowdConstant.ATTR_NAME_EXCEPTION,exception);
        modelAndView.setViewName(viewName);
        return  modelAndView;
    }
}
